﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Prism.Example.Events;
using Microsoft.Practices.Unity;

namespace Prism.Example.ModuleA
{
    [Module(ModuleName = "ModuleAInit")]
    public class ModuleAInit : IModule
    {

        private readonly IUnityContainer _container;
        private readonly IRegionManager _regionManager;
        private readonly IEventAggregator _eventAggregator;

        public ModuleAInit(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator)
        {                    
            this._container = container;
            this._regionManager = regionManager;
            this._eventAggregator = eventAggregator;
        }

        public void Initialize()
        {
            this._container.RegisterType<object, View1>("View1",  new ContainerControlledLifetimeManager());
            _regionManager.AddToRegion("Main", this._container.Resolve(typeof(object), "View1"));

            this._container.RegisterType<ModuleAController>(null, new ContainerControlledLifetimeManager());
            this._container.Resolve<ModuleAController>().Run();
        }

    }

    public class ModuleAController
    {
       private readonly IRegionManager _regionManager;
           private readonly IEventAggregator _eventAggregator;
           public ModuleAController(IRegionManager regionManager, IEventAggregator eventAggregator)
           {
               _regionManager = regionManager;
               _eventAggregator = eventAggregator;

           }

           public void Run()
           {
               _eventAggregator.GetEvent<OnChangeViewEvent>().Subscribe(x => OnChangeViewRequest(x));

           }

        private void OnChangeViewRequest(string viewName)
        {
            if (viewName.Equals("View1"))
            {
                NavigateToView1();

            }
        }

        private void NavigateToView1()
        {
            _regionManager.RequestNavigate("Main", "View1");
        }
    }
}
